package com.baizhiedu.controller;

import com.baizhiedu.entity.User;
import com.baizhiedu.service.UserService;
import com.baizhiedu.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 分页查询方法
    @GetMapping("/findByPage")
    public Map<String, Object> findByPage(Integer pageNow, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        pageNow = pageNow==null? 1:pageNow;
        pageSize = pageSize==null? 4:pageSize;
        List<User> users = userService.findByPage(pageNow, pageSize);
        Long totals = userService.findTotals();

        result.put("users", users);
        result.put("totals", totals);

        return result;
    }

    // 根据id删除一个用户
    @GetMapping("/delete")
    public Result deleteUserById(Integer id) {
        Result result = new Result();
        try {
            userService.deleteUserById(id);
            result.setMsg("删除用户信息成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(false);
            result.setMsg("删除用户信息失败, 请稍后再试！");
        }
        return result;
    }

    // 保存用户信息
    @PostMapping("/savaOrUpdate")
    public Result savaOrUpdate(@RequestBody User user) {
        Result result = new Result();
        try {
            if (StringUtils.isEmpty(user.getId())) {
                userService.addUser(user);
                result.setMsg("用户信息保存成功！");
            } else {
                userService.updateUser(user);
                result.setMsg("用户信息修改成功！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(false);
            result.setMsg("系统错误：保存用户信息失败, 请稍后再试...");
        }
        return result;
    }

    // 查询所有
    @GetMapping("/findAll")
    public List<User> findAll() {
        return userService.findAll();
    }

}
